package cn.sc.allinpay.allfavour.business.common.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

/**
 * @author pany
 * @description activity工具
 * @date 2017年3月4日下午12:02:37
 */
public class ActivityUtils {

    public static void startActivity(Activity activity, Class<?> cls,
                                     Bundle bundle, boolean isFinish) {
        Intent intent = new Intent(activity, cls);
        if (bundle != null)
            intent.putExtras(bundle);
        activity.startActivity(intent);
        if (isFinish)
            activity.finish();
    }

    public static void startActivity(Activity activity, Class<?> cls, boolean isFinish) {
        startActivity(activity, cls, null, isFinish);
    }

    public static void startActivityForResult(Activity activity, Class<?> cls,
                                              int requestCode) {
        Intent intent = new Intent(activity, cls);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startActivityForResult(Activity activity, Class<?> cls,
                                              Bundle bundle, int requestCode) {
        Intent intent = new Intent(activity, cls);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void setResult(Activity activity) {
        Intent intent = new Intent();
        activity.setResult(Activity.RESULT_OK, intent);
    }

    public static void setResult(Activity activity, Bundle bundle, boolean isFinish) {
        Intent intent = new Intent();
        intent.putExtras(bundle);
        activity.setResult(Activity.RESULT_OK, intent);
        if (isFinish) activity.finish();
    }

    /**
     * fragment选项卡切换工具
     *
     * @param <T>
     * @param fm
     * @param crtFrag 当前fragment
     * @param toFrag  要切换到的fragment
     */
    public static <T extends Fragment> T tabSwitchFragment(FragmentManager fm, int fragId,
                                                           T crtFrag, T toFrag) {
        if (crtFrag != toFrag) {
            FragmentTransaction ft = fm.beginTransaction();
            if (!toFrag.isAdded()) {// 判断是否已经添加过
                if (crtFrag != null) {
                    ft.hide(crtFrag).add(fragId, toFrag).commit();// 隐藏当前的fragment,添加选中的fragment
                } else {
                    ft.add(fragId, toFrag).commit();
                }
            } else {
                ft.hide(crtFrag).show(toFrag).commit();// 隐藏当前的fragment,显示选中的fragment
            }
        }
        return toFrag;
    }
}
